﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32;

namespace PassWordManager
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
            //当用户试图注销或关闭系统时发生。  
            SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding);
            string alg=Properties.Settings.Default.algorithm;
            if (string.IsNullOrWhiteSpace(alg))
            {
                encrypt = new AesEncryption();
                count = 16;
            }
            else
            {
                alg=alg.ToLower();
                if ("des".Equals(alg))
                {
                    encrypt = new DesEncryption();
                    count = 8;
                }
                else
                {
                    encrypt = new AesEncryption();
                    count = 16;
                }
            }
        }


        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();

        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
        {
           e.Cancel = true;
        }
        private int count = 8;
        private IEncrypt encrypt;

        private void FrmMain_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks == 1)
            {
                //窗体移动
                if (e.Button == MouseButtons.Left)
                {
                    ReleaseCapture(); //释放鼠标捕捉
                    //发送左键点击的消息至该窗体(标题栏)
                    SendMessage(this.Handle, 0xA1, 0x02, 0);
                }
            }
        }



        private void add_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(saltBox.Text)||saltBox.Text.Length<8)
            {
                MessageBox.Show($"请先填写{count}位以上Salt内容");
                return;
            }
            InputForm form = new InputForm(null, null, new DoWork(doWord), null);
            form.ShowDialog();
        }

        public void doWord(string title, string password, int? lineIndex)
        {
            if (lineIndex!=null)
            {
                DataGridViewRow row = path_dg.Rows[(int)lineIndex];
                row.Cells[0].Value = title;
                row.Cells[1].Value = encrypt.EnCode(password, saltBox.Text);
            }
            else
            {
                int index = path_dg.Rows.Add();
                DataGridViewRow row = path_dg.Rows[index];
                row.Cells[0].Value = title;
                row.Cells[1].Value = encrypt.EnCode(password, saltBox.Text);
            }
        }


        private void delete_Click(object sender, EventArgs e)
        {
            if (path_dg.SelectedRows.Count>0)
            {
                path_dg.Rows.RemoveAt(path_dg.SelectedRows[0].Index);
            }
        }

        private void save_Click(object sender, EventArgs e)
        {
            saveData();
        }

        private void Main_Load(object sender, EventArgs e)
        { 
            LinkedList<string> linkedList = TextFileUtil.getTextLines();
            if (linkedList.Count>0)
            {
                foreach (string line in linkedList)
                {
                    string[] strings = line.Split('$');
                    path_dg.Rows.Add(strings);
                }
            }
        }

        private static readonly string format = "{0}${1}";
        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            saveData();
        }

        private void saveData()
        {
            if (path_dg.Rows.Count > 0)
            {
                LinkedList<string> linkedList = new LinkedList<string>();
                foreach (DataGridViewRow row in path_dg.Rows)
                {
                    linkedList.AddLast(string.Format(format, row.Cells[0].Value,row.Cells[1].Value));
                }

                TextFileUtil.saveTextLines(linkedList);
            }
        }


        private void label1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void label3_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }


        private void path_dg_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            button2_Click(null, null);
        }


        private void button2_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection rowCollection = path_dg.SelectedRows;
            if (rowCollection.Count > 0)
            {
                if (string.IsNullOrWhiteSpace(saltBox.Text))
                {
                    MessageBox.Show(@"请先填写Salt内容");
                    return;
                }
                DataGridViewRow row = rowCollection[0];
                string desc;
                try
                {
                    desc = encrypt.DeCode(row.Cells[1].Value.ToString(), saltBox.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Salt内容不正确，请确认并修改！{ex.Message}");
                    return;
                }
                InputForm form = new InputForm(row.Cells[0].Value.ToString(), desc, doWord, row.Index);
                form.ShowDialog();
            }
            else
            {
                MessageBox.Show(@"请先填选中要修改的行！");
            }


        }

    }
}
